package com.itobase.questionnaire.service.impl;

import com.itobase.questionnaire.dto.UpdateTagFolderDTO;
import com.itobase.questionnaire.exception.BussinessException;
import com.itobase.questionnaire.exception.WrongParameterException;
import com.itobase.questionnaire.model.TagFolder;
import com.itobase.questionnaire.repository.TagFolderRepository;
import com.itobase.questionnaire.repository.TagRepository;
import com.itobase.questionnaire.service.ITagFolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author: lphu
 * @create: 2018-10-18 11:01
 * @description:
 */

@Service
public class TagFolderService implements ITagFolderService
{
    @Autowired
    TagRepository tagRepository;

    @Autowired
    TagFolderRepository tagFolderRepository;

    /**
     * 新建标签夹
     * @param tagFolder
     */
    @Override
    public void addTagFolder(TagFolder tagFolder)
    {
        if (tagFolder.getTagFolderName()=="")
            throw new WrongParameterException("文件名不能为空");
        checkExist(tagFolder.getTagFolderName());
        tagFolderRepository.insert(tagFolder);
    }

    /**
     * 删除标签夹
     * @param tagFolderId
     */
    @Override
    public void deleteTagFolder(String tagFolderId) {
        if (tagRepository.findByTagFolderId(tagFolderId).size()!=0)
            throw new BussinessException("该标签夹下存在标签，不能删除");
        tagFolderRepository.delete(tagFolderId);
    }

    /**
     * 修改标签夹名字
     * @param updateTagFolderDTO
     */
    @Override
    public void updateTagFolder(UpdateTagFolderDTO updateTagFolderDTO) {
        TagFolder tagFolder = Optional.ofNullable(tagFolderRepository.findByTagFolderName(updateTagFolderDTO.getOldTagFolderName()))
                                    .orElseThrow(()->new WrongParameterException("传入参数错误"));
        if (updateTagFolderDTO.getOldTagFolderName()=="")
            throw new BussinessException("标签夹名字不能为空");
        checkExist(updateTagFolderDTO.getNewTagFolderName());
        tagFolder.setTagFolderName(updateTagFolderDTO.getNewTagFolderName());
        tagFolderRepository.save(tagFolder);

    }

    /**
     * 获取标签夹
     * @return
     */
    @Override
    public List<TagFolder> getTagFolderList() {
        return tagFolderRepository.findAll();
    }

    private void checkExist(String tagFolderName){
        TagFolder existTagFolder = tagFolderRepository.findByTagFolderName(tagFolderName);
        if (existTagFolder!=null)
            throw new WrongParameterException("文件名重复");
    }
}
